<template>
  <div class="user-center-container">
    <!-- 添加返回首页按钮 -->
    <div class="back-home">
      <el-button type="primary" plain @click="goHome">
        <el-icon><ArrowLeft /></el-icon>
        返回首页
      </el-button>
    </div>
    
    <el-row :gutter="20">
      <!-- 侧边栏 -->
      <el-col :span="6">
        <el-card class="user-sidebar">
          <div class="user-profile">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :headers="uploadHeaders"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              name="file"
            >
              <el-avatar 
                :size="100" 
                :src="userAvatar" 
                :icon="UserFilled"
                class="user-avatar"
              />
              <div class="avatar-hover-text">更换头像</div>
            </el-upload>
            <h2>{{ userStore.user?.username || '用户名' }}</h2>
            <p>{{ userStore.user?.email || '邮箱地址' }}</p>
          </div>
          
          <el-menu
            :default-active="activeMenu"
            class="user-menu"
            @select="handleMenuSelect"
          >
            <el-menu-item index="profile">
              <el-icon><User /></el-icon>
              <span>个人资料</span>
            </el-menu-item>
            <el-menu-item index="security">
              <el-icon><Lock /></el-icon>
              <span>安全设置</span>
            </el-menu-item>
            <el-menu-item index="comments">
              <el-icon><ChatDotRound /></el-icon>
              <span>我的评论</span>
            </el-menu-item>
            <el-menu-item index="favorites">
              <el-icon><Star /></el-icon>
              <span>我的收藏</span>
            </el-menu-item>
          </el-menu>
        </el-card>
      </el-col>
      
      <!-- 主内容区 -->
      <el-col :span="18">
        <!-- 个人资料 -->
        <el-card v-if="activeMenu === 'profile'" class="content-card">
          <template #header>
            <div class="card-header">
              <h3>个人资料</h3>
              <p>管理您的个人信息</p>
            </div>
          </template>
          
          <el-form 
            ref="profileFormRef"
            :model="profileForm"
            :rules="profileRules"
            label-width="100px"
            class="profile-form"
            v-loading="loading"
          >
            
            <el-form-item label="用户名">
              <el-input v-model="profileForm.username" disabled />
            </el-form-item>
            
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="profileForm.nickname" placeholder="请输入昵称" />
            </el-form-item>
            
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="profileForm.email" placeholder="请输入邮箱" />
            </el-form-item>
            
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="profileForm.phone" placeholder="请输入手机号" />
            </el-form-item>
            
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="profileForm.gender">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
                <el-radio :label="0">保密</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item label="生日" prop="birthday">
              <el-date-picker
                v-model="profileForm.birthday"
                type="date"
                placeholder="选择生日"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
            
            <el-form-item label="常驻城市" prop="location">
              <el-input v-model="profileForm.location" placeholder="请输入常驻城市" />
            </el-form-item>
            
            <el-form-item label="个人简介" prop="bio">
              <el-input
                v-model="profileForm.bio"
                type="textarea"
                :rows="4"
                placeholder="介绍一下自己吧"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="submitForm" :loading="submitting">保存修改</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        
        <!-- 安全设置 -->
        <el-card v-if="activeMenu === 'security'" class="content-card">
          <template #header>
            <div class="card-header">
              <h3>安全设置</h3>
              <p>管理您的账户安全</p>
            </div>
          </template>
          
          <el-form 
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="120px"
            class="password-form"
          >
            <el-form-item label="当前密码" prop="currentPassword">
              <el-input 
                v-model="passwordForm.currentPassword"
                type="password"
                show-password
                placeholder="请输入当前密码"
              />
            </el-form-item>
            
            <el-form-item label="新密码" prop="newPassword">
              <el-input 
                v-model="passwordForm.newPassword"
                type="password"
                show-password
                placeholder="请输入新密码"
              />
            </el-form-item>
            
            <el-form-item label="确认新密码" prop="confirmPassword">
              <el-input 
                v-model="passwordForm.confirmPassword"
                type="password"
                show-password
                placeholder="请再次输入新密码"
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="changeUserPassword" :loading="changingPassword">
                修改密码
              </el-button>
              <el-button @click="resetPasswordForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        
        <!-- 我的评论 -->
        <el-card v-if="activeMenu === 'comments'" class="content-card">
          <template #header>
            <div class="card-header">
              <h3>我的评论</h3>
              <p>管理您发表的评论</p>
            </div>
          </template>
          
          <div v-if="comments.length === 0" class="empty-state">
            <el-empty description="暂无评论" />
          </div>
          
          <div v-else class="comments-list">
            <el-timeline>
              <el-timeline-item
                v-for="comment in comments"
                :key="comment.id"
                :timestamp="formatDate(comment.createTime)"
                placement="top"
              >
                <el-card class="comment-card">
                  <div class="comment-header">
                    <h4>
                      <router-link :to="`/attraction/${comment.attractionId}`">
                        {{ comment.attractionName }}
                      </router-link>
                    </h4>
                    <div class="comment-actions">
                      <el-rate
                        v-model="comment.rating"
                        disabled
                        text-color="#ff9900"
                      />
                      <el-button 
                        type="danger" 
                        size="small" 
                        @click="deleteComment(comment.id)"
                        :loading="deletingComment === comment.id"
                      >
                        删除
                      </el-button>
                    </div>
                  </div>
                  <p class="comment-content">{{ comment.content }}</p>
                </el-card>
              </el-timeline-item>
            </el-timeline>
            
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="commentQuery.pageNum"
                v-model:page-size="commentQuery.pageSize"
                :page-sizes="[5, 10, 20, 50]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="commentTotal"
                @size-change="loadComments"
                @current-change="loadComments"
              />
            </div>
          </div>
        </el-card>
        
        <!-- 我的收藏 -->
        <el-card v-if="activeMenu === 'favorites'" class="content-card">
          <template #header>
            <div class="card-header">
              <h3>我的收藏</h3>
              <p>管理您收藏的景点</p>
            </div>
          </template>
          
          <div v-if="favorites.length === 0" class="empty-state">
            <el-empty description="暂无收藏" />
          </div>
          
          <div v-else class="favorites-list">
            <el-row :gutter="20">
              <el-col 
                v-for="favorite in favorites" 
                :key="favorite.id"
                :xs="24" 
                :sm="12" 
                :md="8" 
                :lg="8"
              >
                <el-card class="favorite-card" :body-style="{ padding: '0px' }">
                  <img :src="favorite.imageUrl || require('@/assets/placeholder.jpg')" class="favorite-image" />
                  <div class="favorite-info">
                    <h4>
                      <router-link :to="`/attraction/${favorite.attractionId}`">
                        {{ favorite.name }}
                      </router-link>
                    </h4>
                    <div class="favorite-meta">
                      <span>
                        <el-icon><Location /></el-icon>
                        {{ favorite.location }}
                      </span>
                      <el-rate
                        v-model="favorite.rating"
                        disabled
                        text-color="#ff9900"
                        size="small"
                      />
                    </div>
                    <div class="favorite-actions">
                      <el-button 
                        type="primary" 
                        size="small"
                        @click="viewAttraction(favorite.attractionId)"
                      >
                        查看详情
                      </el-button>
                      <el-button 
                        type="danger" 
                        size="small"
                        @click="removeFavoriteItem(favorite.attractionId)"
                        :loading="removingFavorite === favorite.attractionId"
                      >
                        取消收藏
                      </el-button>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
            
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="favoriteQuery.page"
                v-model:page-size="favoriteQuery.size"
                :page-sizes="[6, 12, 24, 48]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="favoriteTotal"
                @size-change="loadFavorites"
                @current-change="loadFavorites"
              />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  User, 
  Lock, 
  Star, 
  ChatDotRound, 
  UserFilled, 
  Location, 
  Calendar,
  ArrowLeft
} from '@element-plus/icons-vue';
import { useUserStore } from '@/stores/user';
import { 
  getUserInfo, 
  updateUserInfo, 
  changePassword, 
  getUserFavorites, 
  uploadAvatar, 
  deleteUserComment, 
  removeFavorite 
} from '@/api/user';
import { formatDate } from '@/utils/format';
import { getUserComments } from '@/api/comment';

const router = useRouter();
const userStore = useUserStore();
const activeMenu = ref('profile');

// 添加返回首页方法
const goHome = () => {
  router.push('/');
};

// 用户头像
const userAvatar = ref(userStore.user?.avatar || '');
// 根据接口文档更新上传URL
const uploadUrl = `${import.meta.env.VITE_API_BASE_URL}/file/avatar`;
const uploadHeaders = {
  Authorization: `Bearer ${localStorage.getItem('token')}`
};

// 个人资料表单
const profileFormRef = ref(null);
const loading = ref(false);
const submitting = ref(false);
const profileForm = reactive({
  username: '',
  nickname: '',
  email: '',
  phone: '',
  avatar: '',
  gender: 0,
  birthday: '',
  location: '',
  bio: ''
});

// 头像URL
const avatarUrl = computed(() => {
  if (profileForm.avatar) {
    // 如果头像是完整URL则直接使用，否则拼接API基础URL
    if (profileForm.avatar.startsWith('http')) {
      return profileForm.avatar;
    } else {
      return `${import.meta.env.VITE_API_BASE_URL}/file/avatar/${profileForm.avatar}`;
    }
  }
  return '';
});

// 个人资料验证规则
const profileRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  bio: [
    { max: 500, message: '个人简介不能超过500个字符', trigger: 'blur' }
  ]
};

// 密码表单
const passwordFormRef = ref(null);
const changingPassword = ref(false);
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
});

// 密码验证规则
const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 8, message: '密码长度不能小于8个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

// 评论相关状态
const comments = ref([]);
const commentTotal = ref(0);
const commentQuery = reactive({
  pageNum: 1,
  pageSize: 5
});
const deletingComment = ref(null);

// 收藏列表
const favorites = ref([]);
const favoritesLoading = ref(false);
const favoritesCurrentPage = ref(1);
const favoritesPageSize = ref(8);
const favoritesTotal = ref(0);
const removingFavorite = ref(null);

// 加载用户信息 - 根据接口文档更新
const loadUserInfo = async () => {
  try {
    const response = await getUserInfo();
    
    if (response.code === 200 && response.data) {
      const userData = response.data;
      
      // 更新表单数据
      profileForm.username = userData.username || '';
      profileForm.nickname = userData.nickname || '';
      profileForm.email = userData.email || '';
      profileForm.phone = userData.phone || '';
      profileForm.avatar = userData.avatar || '';
      profileForm.gender = userData.gender || 0;
      profileForm.birthday = userData.birthday || '';
      profileForm.location = userData.location || '';
      profileForm.bio = userData.bio || '';
      
      // 更新头像
      if (userData.avatar) {
        userAvatar.value = userData.avatar;
      }
      
      // 更新用户存储
      userStore.user = userData;
      localStorage.setItem('user', JSON.stringify(userData));
    } else {
      ElMessage.error(response.message || '获取用户信息失败');
    }
  } catch (error) {
    console.error('获取用户信息出错:', error);
    ElMessage.error('获取用户信息失败，请稍后再试');
  }
};

// 更新个人资料 - 根据接口文档更新
const submitForm = async () => {
  await profileFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    submitting.value = true;
    
    try {
      const response = await updateUserInfo(profileForm);
      
      if (response.code === 200) {
        ElMessage.success('个人资料更新成功');
        
        // 更新用户存储
        if (userStore.user) {
          userStore.user = {
            ...userStore.user,
            ...profileForm
          };
          localStorage.setItem('user', JSON.stringify(userStore.user));
        }
      } else {
        ElMessage.error(response.message || '更新个人资料失败');
      }
    } catch (error) {
      console.error('更新个人资料出错:', error);
      ElMessage.error('更新个人资料失败，请稍后再试');
    } finally {
      submitting.value = false;
    }
  });
};

// 重置个人资料表单
const resetForm = () => {
  profileFormRef.value.resetFields();
  loadUserInfo(); // 重新加载用户信息
};

// 修改密码 - 根据接口文档更新
const changeUserPassword = async () => {
  await passwordFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    changingPassword.value = true;
    
    try {
      const response = await changePassword({
        oldPassword: passwordForm.currentPassword,
        newPassword: passwordForm.newPassword
      });
      
      if (response.code === 200) {
        ElMessage.success('密码修改成功');
        resetPasswordForm();
      } else {
        ElMessage.error(response.message || '密码修改失败');
      }
    } catch (error) {
      console.error('密码修改出错:', error);
      ElMessage.error('密码修改失败，请稍后再试');
    } finally {
      changingPassword.value = false;
    }
  });
};

// 重置密码表单
const resetPasswordForm = () => {
  passwordFormRef.value.resetFields();
};

// 加载评论列表 - 根据接口文档更新
const loadComments = async () => {
  try {
    const response = await getUserComments({
      pageNum: commentQuery.pageNum,
      pageSize: commentQuery.pageSize
    });
    
    if (response.code === 200) {
      comments.value = response.data.list || [];
      commentTotal.value = response.data.total || 0;
    } else {
      ElMessage.error('获取评论失败: ' + response.message);
    }
  } catch (error) {
    console.error('获取评论失败:', error);
    ElMessage.error('获取评论失败，请稍后再试');
  }
};

// 删除评论
const deleteComment = async (commentId) => {
  try {
    deletingComment.value = commentId;
    
    await ElMessageBox.confirm(
      '确定要删除这条评论吗？此操作不可恢复。',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    const response = await deleteUserComment(commentId);
    
    if (response.code === 200) {
      ElMessage.success('评论已删除');
      loadComments(); // 重新加载评论列表
    } else {
      ElMessage.error('删除评论失败: ' + response.message);
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除评论失败:', error);
      ElMessage.error('删除评论失败，请稍后再试');
    }
  } finally {
    deletingComment.value = null;
  }
};

// 加载收藏列表 - 根据接口文档更新
const loadFavorites = async () => {
  favoritesLoading.value = true;
  
  try {
    const response = await getUserFavorites({
      page: favoritesCurrentPage.value,
      size: favoritesPageSize.value
    });
    
    if (response.code === 200 && response.data) {
      favorites.value = response.data.records || [];
      favoritesTotal.value = response.data.total || 0;
    } else {
      ElMessage.error('获取收藏列表失败');
    }
  } catch (error) {
    console.error('获取收藏列表出错:', error);
    ElMessage.error('获取收藏列表失败，请稍后再试');
  } finally {
    favoritesLoading.value = false;
  }
};

// 取消收藏 - 根据接口文档更新
const removeFavoriteItem = async (attractionId) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消收藏这个景点吗？',
      '取消收藏',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    removingFavorite.value = attractionId;
    
    try {
      const response = await removeFavorite(attractionId);
      
      if (response.code === 200) {
        ElMessage.success('已取消收藏');
        loadFavorites(); // 重新加载收藏列表
      } else {
        ElMessage.error(response.message || '取消收藏失败');
      }
    } catch (error) {
      console.error('取消收藏出错:', error);
      ElMessage.error('取消收藏失败，请稍后再试');
    } finally {
      removingFavorite.value = null;
    }
  } catch {
    // 用户取消操作
  }
};

// 查看景点详情
const viewAttraction = (id) => {
  router.push(`/attraction/${id}`);
};

// 处理菜单选择
const handleMenuSelect = (index) => {
  activeMenu.value = index;
  
  // 根据选择的菜单加载相应的数据
  if (index === 'comments') {
    loadComments();
  } else if (index === 'favorites') {
    loadFavorites();
  }
};

// 头像上传成功回调
const handleAvatarSuccess = (response, uploadFile) => {
  if (response.code === 200) {
    // 更新头像URL - 注意这里response.data直接就是URL字符串
    userAvatar.value = response.data;
    // 同时更新profileForm中的avatar字段，确保提交表单时能传递给后端
    profileForm.avatar = response.data;
    ElMessage.success('头像上传成功');
  } else {
    ElMessage.error(response.message || '头像上传失败');
  }
};

// 头像上传前的验证 - 根据接口文档更新
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;
  
  if (!isImage) {
    ElMessage.error('头像必须是图片格式!');
    return false;
  }
  
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!');
    return false;
  }
  
  return true;
};

// 页面加载时获取用户信息
onMounted(() => {
  loadUserInfo();
  if (activeMenu.value === 'comments') {
    loadComments();
  }
});

// 监听菜单切换，当切换到评论时加载评论数据
watch(activeMenu, (newValue) => {
  if (newValue === 'comments') {
    loadComments();
  }
});
</script>

<style scoped>
.user-center-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

/* 添加返回首页按钮样式 */
.back-home {
  margin-bottom: 20px;
}

.back-home .el-button {
  display: flex;
  align-items: center;
}

.back-home .el-icon {
  margin-right: 5px;
}

.user-sidebar {
  margin-bottom: 20px;
}

.user-profile {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
  border-bottom: 1px solid #eee;
}

.avatar-uploader {
  position: relative;
  margin-bottom: 15px;
  cursor: pointer;
}

.user-avatar {
  display: block;
  margin: 0 auto;
  border: 2px solid #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.avatar-hover-text {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  border-radius: 50%;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-uploader:hover .avatar-hover-text {
  opacity: 1;
}

.user-profile h2 {
  margin: 10px 0 5px;
  font-size: 18px;
}

.user-profile p {
  color: #909399;
  font-size: 14px;
  margin: 0;
}

.user-menu {
  border-right: none;
}

.content-card {
  margin-bottom: 20px;
}

.card-header {
  margin-bottom: 20px;
}

.card-header h3 {
  margin: 0 0 5px;
  font-size: 18px;
}

.card-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.profile-form,
.password-form {
  max-width: 500px;
}

.empty-state {
  padding: 40px 0;
}

.comments-list,
.favorites-list {
  margin-top: 20px;
}

.comment-card {
  margin-bottom: 10px;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.comment-header h4 {
  margin: 0;
}

.comment-content {
  color: #606266;
  line-height: 1.6;
}

.favorite-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.favorite-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.favorite-image {
  width: 100%;
  height: 180px;
  object-fit: cover;
}

.favorite-info {
  padding: 15px;
}

.favorite-info h4 {
  margin: 0 0 10px;
  font-size: 16px;
}

.favorite-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  color: #909399;
  font-size: 14px;
}

.favorite-meta span {
  display: flex;
  align-items: center;
}

.favorite-meta .el-icon {
  margin-right: 5px;
}

.favorite-actions {
  display: flex;
  justify-content: space-between;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .user-center-container {
    padding: 0 10px;
  }
  
  .el-row {
    display: flex;
    flex-direction: column;
  }
  
  .el-col {
    width: 100% !important;
    max-width: 100% !important;
  }
}
</style> 